﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebMvc.Controllers
{
    public class LoginController : MyController
    {
        [MyAttribute(CheckApp = false, CheckLogin = false, CheckUrl = false)]
        public ActionResult Index()
        {
            return View();
        }

        [MyAttribute(CheckApp = false, CheckLogin = false, CheckUrl = false)]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [MyAttribute(CheckApp = false, CheckLogin = false, CheckUrl = false)]
        public string ValidateLogin()
        {
            string account = Request.Form["Account"];
            string password = Request.Form["Password"];
            if (account.IsNullOrEmpty() || password.IsNullOrEmpty())
            {
                return "{\"id\":\"\",\"status\":0,\"msg\":\"帐号或密码不能为空\"}";
            }


            YJ.Platform.Users busers = new YJ.Platform.Users();
            var user = busers.GetByAccount(account.Trim());
            if (user == null || string.Compare(user.Password, busers.GetUserEncryptionPassword(user.ID.ToString(), password.Trim()), false) != 0)
            {
                return "{\"id\":\"\",\"status\":0,\"msg\":\"帐号或密码错误\"}";
            }
            if (user.Status == 1)
            {
                return "{\"id\":\"\",\"status\":0,\"msg\":\"帐号已被冻结\"}";
            }

            Session[YJ.Utility.Keys.SessionKeys.UserID.ToString()] = user.ID;
            Session[YJ.Utility.Keys.SessionKeys.BaseUrl.ToString()] = Url.Content("~/");
            Session[YJ.Utility.Keys.SessionKeys.UserName.ToString()] = user.Name;
            Response.Cookies.Add(new HttpCookie(YJ.Utility.Keys.SessionKeys.UserID.ToString(), user.ID.ToString()) { Expires = CurrentDateTime.AddDays(7) });
            YJ.Platform.Log.Add("用户登录成功-test" + "(帐号:" + account + ")", "", YJ.Platform.Log.Types.用户登录);
            return "{\"id\":\"" + user.ID.ToString() + "\",\"token\":\"" + YJ.Utility.Config.GetTokenByUserId(user.ID) + "\",\"status\":1,\"msg\":\"用户登录成功\"}";
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [MyAttribute(CheckApp = false, CheckLogin = false, CheckUrl = false)]
        public string CheckLogin()
        {
            string isVcodeSessionKey = YJ.Utility.Keys.SessionKeys.IsValidateCode.ToString();
            string vcodeSessionKey = YJ.Utility.Keys.SessionKeys.ValidateCode.ToString();
            string account = Request.Form["Account"];
            string password = Request.Form["Password"];
            string vcode = Request.Form["VCode"];
            string force = Request.Form["Force"];//是否强行登录

            string logMsg = "(帐号:" + account + " 密码:" + password + " 验证码:" + vcode + ")";
            if (account.IsNullOrEmpty() || password.IsNullOrEmpty())
            {
                YJ.Platform.Log.Add("用户登录失败(帐号或密码为空)" + logMsg, "", YJ.Platform.Log.Types.用户登录);
                return "{\"status\":0,\"msg\":\"帐号或密码不能为空!\"}";
            }
            if (Session[isVcodeSessionKey] != null && "1" == Session[isVcodeSessionKey].ToString() &&
                (Session[vcodeSessionKey] == null
                || string.Compare(Session[vcodeSessionKey].ToString(), vcode.Trim1(), true) != 0))
            {
                YJ.Platform.Log.Add("用户登录失败(验证码错误)" + logMsg, "", YJ.Platform.Log.Types.用户登录);
                return "{\"status\":0,\"msg\":\"验证码错误!\"}";
            }

            YJ.Platform.Users busers = new YJ.Platform.Users();
            var user = busers.GetByAccount(account.Trim());
            if (user == null || string.Compare(user.Password, busers.GetUserEncryptionPassword(user.ID.ToString(), password.Trim()), false) != 0)
            {
                Session[isVcodeSessionKey] = "1";
                YJ.Platform.Log.Add("用户登录失败(帐号或密码错误)" + logMsg, "", YJ.Platform.Log.Types.用户登录);
                return "{\"status\":0,\"msg\":\"帐号或密码错误!\"}";
            }
            if (user.Status == 1)
            {
                Session[isVcodeSessionKey] = "1";
                YJ.Platform.Log.Add("用户登录失败(帐号已被冻结)" + logMsg, "", YJ.Platform.Log.Types.用户登录);
                return "{\"status\":0,\"msg\":\"帐号已被冻结!\"}";
            }
            YJ.Platform.OnlineUsers bou = new YJ.Platform.OnlineUsers();
            var onUser = bou.Get(user.ID);
            if (onUser != null && "1" != force)
            {
                string ip = onUser.IP;
                Session.Remove(isVcodeSessionKey);
                return "{\"status\":2,\"msg\":\"当前帐号已经在" + ip + "登录,您要强行登录吗?\"}";
            }

            Guid uniqueID = Guid.NewGuid();
            Session[YJ.Utility.Keys.SessionKeys.UserID.ToString()] = user.ID;
            Session[YJ.Utility.Keys.SessionKeys.UserUniqueID.ToString()] = uniqueID;
            Session[YJ.Utility.Keys.SessionKeys.BaseUrl.ToString()] = Url.Content("~/");
            Session[YJ.Utility.Keys.SessionKeys.UserName.ToString()] = user.Name;
            Response.Cookies.Add(new HttpCookie(YJ.Utility.Keys.SessionKeys.UserID.ToString(), user.ID.ToString()) { Expires = CurrentDateTime.AddDays(7) });
            bou.Add(user, uniqueID);
            Session.Remove(isVcodeSessionKey);
            YJ.Platform.Log.Add("用户登录成功" + "(帐号:" + account + ")", "", YJ.Platform.Log.Types.用户登录);
            return "{\"status\":1,\"msg\":\"成功!\"}";
        }

        [MyAttribute(CheckApp = false, CheckLogin = false)]
        public void VCode()
        {
            string code;
            System.IO.MemoryStream ms = YJ.Utility.Tools.GetValidateImg(out code, Url.Content("~/Images/vcodebg.png"));
            System.Web.HttpContext.Current.Session[YJ.Utility.Keys.SessionKeys.ValidateCode.ToString()] = code;
            Response.ClearContent();
            Response.ContentType = "image/gif";
            Response.BinaryWrite(ms.ToArray());
        }

        [MyAttribute(CheckApp = false, CheckLogin = false, CheckUrl = false)]
        public ActionResult Quit()
        {
            new YJ.Platform.OnlineUsers().Remove(YJ.Platform.Users.CurrentUserID);
            Session.RemoveAll();
            string cookieName = YJ.Utility.Keys.SessionKeys.UserID.ToString();
            Response.Cookies[cookieName].Expires = DateTime.Now.AddDays(-1);
            Response.Cookies[cookieName].Value = "";
            return Redirect("~/Login");
        }
    }
}
